package com.xoa.service.cms;

import com.xoa.model.cms.CmsChannelInfo;
import com.xoa.model.cms.CmsSiteInfo;
import com.xoa.model.cms.SiteTemplateModel;
import com.xoa.model.enclosure.Attachment;
import com.xoa.service.cms.core.CmsTemplateUtil;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.util.GetAttachmentListUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * Created by cyt on 2018/7/7.
 */
@Service
public class CmsChannelPublishService {
    @Autowired
    private CmsSiteService siteService;

    @Autowired
    private CmsSiteTemplateService siteTemplateService;

    @Autowired
    private CmsChannelService channelService;

    @Autowired
    private CmsDocumentService documentService;

    @Autowired
    private CmsDocumentPublishService docPublishService;


    @Autowired
    private CmsSitePublishService sitePublishService;

    @Autowired
    private EnclosureService attachmentService;
    /**
     * 栏目发布（包括栏目下所有文章）
     * @param channelId
     * @param fullPub
     */
    public void toPub(HttpServletRequest request,int channelId, boolean fullPub) {
        //获取站点信息
        CmsChannelInfo channelInfo = channelService.getChannelInfo(channelId);
        CmsSiteInfo siteInfo = siteService.getSiteInfo(channelInfo.getSiteId());
        //获取站点模板
        SiteTemplateModel indexTpl = siteTemplateService.getSiteTemplate(channelInfo.getIndexTpl());
//        ResourceBundle rb =  ResourceBundle.getBundle("cms");
        if(indexTpl!=null){//如果存在首页模板，则进行渲染
            String pathsrc=request.getRealPath("cmstpls");
//            String path = rb.getString("rootPath")+ System.getProperty("file.separator")+indexTpl.getSiteId();
            String path = pathsrc+ System.getProperty("file.separator")+indexTpl.getSiteId();
            Configuration config=new Configuration();
            ByteArrayOutputStream baos = null;
            Writer out = null;
            FileOutputStream fos=null;
            try {
                List<Map> docList = documentService.getPublishableDocumentsByChnlId(channelId,0, Integer.MAX_VALUE,null,null);
                int pageSize=channelInfo.getPageSize()==0? Integer.MAX_VALUE:channelInfo.getPageSize();
                int pageNums =0;
                int curPage=1;
                pageNums = (docList.size())%pageSize==0?(docList.size())/pageSize:(docList.size())/pageSize+1;
                config.setDirectoryForTemplateLoading(new File(path));
                //注入服务
                config.setCustomAttribute("siteService", siteService);
                config.setCustomAttribute("siteTemplateService", siteTemplateService);
                config.setCustomAttribute("channelService", channelService);
                config.setCustomAttribute("documentService", documentService);
                config.setCustomAttribute("attachmentService", attachmentService);
                config.setCustomAttribute("preview", false);

                //附加参数
                config.setCustomAttribute("ROOT_PATH", channelService.getChannelRootPath(channelId));
                config.setCustomAttribute("SITE_ID", channelInfo.getSiteId());
                config.setCustomAttribute("CHANNEL_ID", channelId);

                //每一页数据条数
                config.setCustomAttribute("pageSize", pageSize);
                config.setCustomAttribute("pageNums", pageNums);

                config.setSharedVariable("curChannelId", channelId);

                Template template=config.getTemplate(indexTpl.getTplFileName(),"UTF-8");

                List<CmsChannelInfo> channels = new ArrayList<CmsChannelInfo>();
                channels = channelService.getChildChannels(channelId, Integer.MAX_VALUE);
                if(null!=channels && channels.size()>0){
                    for(CmsChannelInfo info:channels){
                        toPub(request,info.getSid(),true);
                    }
                }
                //生成对应的静态文件
                String outPath = channelService.getChannelAbsolutePath(channelInfo.getSid())+"/";
                File file = new File(outPath);
                if(!file.exists()){
                    file.mkdirs();
                }
                String destPath="";
                for(int k=0;k<pageNums;k++){
                    if(k==0){
                        destPath=outPath+"index."+siteInfo.getPubFileExt();
                    }else{
                        destPath=outPath+"index"+k+"."+siteInfo.getPubFileExt();
                    }
                    baos = new ByteArrayOutputStream();
                    out = new OutputStreamWriter(baos,"UTF-8");
                    config.setCustomAttribute("curPage", curPage);
                    template.process(CmsTemplateUtil.getInstance(), out);
                    fos = new FileOutputStream(new File(destPath));
                    baos.writeTo(fos);
                    curPage++;
                    out.flush();
                    baos.flush();
                }
                if(pageNums==0){
                    destPath=outPath+"index."+siteInfo.getPubFileExt();
                    baos = new ByteArrayOutputStream();
                    out = new OutputStreamWriter(baos,"UTF-8");
                    template.process(CmsTemplateUtil.getInstance(), out);
                    fos = new FileOutputStream(new File(destPath));
                    baos.writeTo(fos);
                    out.flush();
                    baos.flush();
                }

                //获取附件并发布到对应的目录中
                List<Attachment> attaches =null;
                //attaches =channelService.getAttachmentDao().getAttaches(TeeAttachmentModelKeys.cmsChannel, String.valueOf(channelId));
                attaches= GetAttachmentListUtil.returnAttachment("","","xoa1001", GetAttachmentListUtil.MODULE_EMAIL);
                for (Attachment attach : attaches) {
                   // String srcPath = attach.getAttachSpace().getSpacePath()+"/"+attach.getModel()+"/"+attach.getAttachmentPath()+"/"+attach.getAttachmentName();
                    String srcPath = attach.getPath()+"/"+attach.getModule()+"/"+attach.getAttUrl()+"/"+attach.getAttachName();
                    InputStream ins = new FileInputStream(srcPath);
                    //String destPath0=siteInfo.getFolder()+"/attach/"+attach.getModel()+"/"+attach.getAttachmentPath()+"/"+attach.getAttachmentName();
                    //String destPath0=siteInfo.getFolder()+"/attach/"+attach.getModule()+"/"+attach.getAttUrl()+"/"+attach.getAttachName();
                    String destPath0=siteInfo.getFolder()+attach.getModule()+"/"+attach.getAttUrl()+"/"+attach.getAttachName();
                    saveFile(ins, destPath0);
                    ins.close();
                }

                //发布栏目下所有文章
                if(fullPub){
                    for(int i=0;i<docList.size();i++){
                        docPublishService.toPub(request,(Integer)docList.get(i).get("chnlDocId"), false);
                    }
                }
                sitePublishService.toPub(request,channelInfo.getSiteId(), false);
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(baos!=null){
                    try {
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                    }
                }
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    public static void saveFile(InputStream inputStream, String savePath)
            throws IOException {
        if (savePath == null) {
            return;
        }
        File outFile = new File(savePath);
        File outPath = outFile.getParentFile();
        if (!outPath.exists()) {
            outPath.mkdirs();
        }
        if (!outFile.exists()) {
            outFile.createNewFile();
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(inputStream);
            out = new BufferedOutputStream(new FileOutputStream(outFile));
            byte[] buff = new byte[1024*1024];
            int length = 0;
            while ((length = in.read(buff)) > 0) {
                out.write(buff, 0, length);
                out.flush();
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception ex) {
            }
        }
    }
}
